import { wptBridgeJsCallNative, wptBridgeRegisterForNativeJs, wptBridgeJsCallBack } from './core';

export default {
    //注册方法用于让APP调用
    register(name, cb) {
        return wptBridgeRegisterForNativeJs(name, cb);
    },
    //js调用app中的方法，支持超时
    call(name, param, success, fail, timeout = 3000) {
        let timer = setTimeout(() => {
            fail && fail();
            timer = null;
        }, timeout);
        wptBridgeJsCallNative(
            name,
            param,
            (res) => {
                if (timer === null) {
                    return;
                }
                clearTimeout(timer);
                success && success(res);
            },
            () => {
                if (timer === null) {
                    return;
                }
                clearTimeout(timer);
                fail && fail();
            }
        );
    },
    //js回调app的方法
    callBack(name, params) {
        wptBridgeJsCallBack({ eventId: name, params });
    },
    //call方法的promise版本
    send(name, param, timeout = 3000) {
        return new Promise((resolve, reject) => {
            this.call(
                name,
                param,
                ({ code, msg, data }) => {
                    if (code === 0) {
                        resolve(data);
                    } else {
                        reject(msg);
                    }
                },
                reject,
                timeout
            );
        });
    },
};
